<?php
require_once IA_ROOT . '/addons/xn_erp/inc/class/db_common.php';

function DB($db)
{
    return load_class($db, 'db_');
}

function load_class($name, $prefix = '')
{
    $file = IA_ROOT . '/addons/xn_erp/inc/class/' . $prefix . $name . '.php';
    if (is_file($file)) {
        require_once $file;
    }
    $load = new $name();
    return $load;
}

function ejson_encode($array)
{
    header('Content-type:text/json');
    return json_encode($array);
}

function xn_json($data = array(), $count = 0, $msg = '', $code = '0')
{
    $array = array(
        "code" => $code,
        "msg" => $msg,
        "count" => $count,
        "data" => $data,
    );
    return ejson_encode($array);

}
function in_storage_by_goods($goods, $storageid)
{
    foreach ($goods as $key => $value) {
        if ($value['snumber'] > 0) {

            $good_num_arr = pdo_get('xn_erp_goods_num', array('gid' => $value['id'], 'sid' => $storageid));

            $arr = array(
                'gid' => $value['id'],
                'sid' => $storageid,
                'num' => $value['snumber'],
                'edittime' => TIMESTAMP,
            );
            if ($good_num_arr['id']) {
                $arr['num'] = $good_num_arr['num'] + $value['snumber'];
                pdo_update('xn_erp_goods_num', $arr, array('id' => $good_num_arr['id']));
            } else {
                pdo_insert('xn_erp_goods_num', $arr);
            }
        }
    }
}
function out_storage_by_goods($goods)
{

}
function checkstorage($goods, $outid)
{
    $return = array();
    foreach ($goods as $key => $value) {
        if ($value['snumber'] > 0) {
            $good_num_arr = pdo_get('xn_erp_goods_num', array('gid' => $value['id'], 'sid' => $outid));
            //剩余的库存
            $storage_num = $good_num_arr['num'] - $good_num_arr['down'];

            if ($value['snumber'] > $storage_num) {
                $return = array('code' => -1, 'msg' => showmessage('出库失败请检查库存，商品编号：' . $value['number'], 'error'));
            }
        } else {
            $return = array('code' => -1, 'msg' => showmessage('添加失败，请填写商品个数！', 'error'));
        }
    }
    return $return;
}

function showmessage($content, $type = 'success', $icon = '', $color = '')
{

    switch ($type) {
        case 'success':
            $i = '&#xe6af;';
            $c = '#1E9FFF';
            break;
        case 'error':
            $i = '&#xe69c;';
            $c = '#FF5722';
            break;
        case 'warning':
            $i = '&#xe664;';
            $c = '#FFB800';
            break;
        default:
            break;
    }
    $icon = $icon ? $icon : $i;
    $color = $color ? $color : $c;
    $msg = '<i class="layui-icon" style="margin-right: 5px; color: ' . $color . ';">' . $icon . '</i>' . $content;
    return $msg;
}

if (!function_exists('list_to_tree')) {
    /**
     * 把返回的数据集转换成Tree
     * @param array $list 要转换的数据集
     * @param string $pid parent标记字段
     * @param string $level level标记字段
     * @return array
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] = &$list[$key];
            }

            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] = &$list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent = &$refer[$parentId];
                        $parent[$child][] = &$list[$key];
                    }
                }
            }
        }
        return $tree;
    }
}
function xn_tpl_form_field_multi_image($name, $value = array(), $options = array())
{
    global $_W;
    $options['multiple'] = true;
    $options['direct'] = false;
    $options['fileSizeLimit'] = intval($GLOBALS['_W']['setting']['upload']['image']['limit']) * 1024;
    if (isset($options['dest_dir']) && !empty($options['dest_dir'])) {
        if (!preg_match('/^\w+([\/]\w+)?$/i', $options['dest_dir'])) {
            exit('图片上传目录错误,只能指定最多两级目录,如: "we7_store","we7_store/d1"');
        }
    }
    $s = '';
    if (!defined('TPL_INIT_MULTI_IMAGE')) {
        $s = '
<script type="text/javascript">
	function uploadMultiImage(elm) {
		var name = $(elm).next().val();
		util.image( "", function(urls){
			$.each(urls, function(idx, url){
				$(elm).parent().parent().next().append(\'<div class="multi-item"><img onerror="this.src=\\\'./resource/images/nopic.jpg\\\'; this.title=\\\'图片未找到.\\\'" src="\'+url.url+\'" class="img-responsive img-thumbnail"><input type="hidden" name="\'+name+\'[]" value="\'+url.attachment+\'"><em class="close" title="删除这张图片" onclick="deleteMultiImage(this)">×</em></div>\');
			});
		}, ' . json_encode($options) . ');
	}
	function deleteMultiImage(elm){
		$(elm).parent().remove();
	}
</script>';
        define('TPL_INIT_MULTI_IMAGE', true);
    }

    $s .= <<<EOF
<div class="input-group">

	<span class="input-group-btn">
		<button class="btn btn-default" type="button" onclick="uploadMultiImage(this);">选择图片</button>
		<input type="hidden" value="{$name}" />
	</span>
</div>
<div class="input-group multi-img-details">
EOF;
    if (is_array($value) && count($value) > 0) {
        foreach ($value as $row) {
            $s .= '
<div class="multi-item">
	<img src="' . tomedia($row) . '" onerror="this.src=\'./resource/images/nopic.jpg\'; this.title=\'图片未找到.\'" class="img-responsive img-thumbnail">
	<input type="hidden" name="' . $name . '[]" value="' . $row . '" >
	<em class="close" title="删除这张图片" onclick="deleteMultiImage(this)">×</em>
</div>';
        }
    }
    $s .= '</div>';

    return $s;
}
